<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>人力资源管理系统 - 技能管理</title>
  <!-- 引入外部资源 -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

  <!-- Tailwind配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#2563eb',
            secondary: '#64748b',
            success: '#10b981',
            warning: '#f59e0b',
            danger: '#ef4444',
            dark: '#1e293b',
            light: '#f8fafc'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 引入公共CSS -->
  <link rel="stylesheet" href="css/common.css">

  <!-- 引入API和公共JS -->
  <script src="js/api.js"></script>
  <script src="js/common.js"></script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .skill-card {
        @apply bg-white rounded-xl shadow-sm border border-gray-100 p-5 hover:shadow-md transition-shadow duration-300;
      }
      .btn-action {
        @apply px-3 py-1 rounded-lg text-sm font-medium transition-all duration-200 cursor-pointer;
      }
    }
  </style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans">
  <div id="app" class="flex h-screen overflow-hidden">
    <!-- 侧边栏 -->
    <aside id="sidebar" class="w-64 bg-white border-r border-gray-200 flex-shrink-0 hidden md:block transition-all duration-300">
      <div class="p-5 border-b border-gray-200">
        <h1 class="text-xl font-bold text-primary">人力资源管理系统</h1>
      </div>

      <nav class="p-3">
        <ul>
          <li>
            <a href="index.html" class="sidebar-item">
              <i class="fa fa-dashboard"></i>
              <span>仪表盘</span>
            </a>
          </li>
          <li>
            <a href="projects.html" class="sidebar-item">
              <i class="fa fa-briefcase"></i>
              <span>项目中心</span>
            </a>
          </li>
          <li>
            <a href="employees.html" class="sidebar-item">
              <i class="fa fa-users"></i>
              <span>员工管理</span>
            </a>
          </li>
          <li>
            <a href="tasks.html" class="sidebar-item">
              <i class="fa fa-tasks"></i>
              <span>任务管理</span>
            </a>
          </li>
          <li>
            <a href="skill-management.html" class="sidebar-item active">
              <i class="fa fa-cogs"></i>
              <span>技能管理</span>
            </a>
          </li>
          <li>
            <a href="reports.html" class="sidebar-item">
              <i class="fa fa-bar-chart"></i>
              <span>分析报表</span>
            </a>
          </li>
        </ul>
      </nav>

      <div class="absolute bottom-0 w-full p-4 border-t border-gray-200">
        <div class="flex items-center gap-3">
          <img id="userAvatar" src="https://picsum.photos/200/200?random=1" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
          <div>
            <p id="user" class="font-medium text-sm">张三</p>
            <p id="userRole" class="text-xs text-gray-500">项目经理</p>
          </div>
          <button id="logoutBtn" class="ml-auto text-gray-500 hover:text-danger">
            <i class="fa fa-sign-out"></i>
          </button>
        </div>
      </div>
    </aside>

    <!-- 主内容区 -->
    <main class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部导航 -->
      <header class="bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between">
        <div class="flex items-center gap-3">
          <button id="sidebarToggle" class="md:hidden text-gray-500 hover:text-primary">
            <i class="fa fa-bars"></i>
          </button>
          <h2 class="text-lg font-semibold">技能管理</h2>
        </div>

        <div class="flex items-center gap-3">
          <div class="relative hidden md:block">
            <input type="text" placeholder="搜索..." class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary w-64">
            <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500"></i>
          </div>

          <button class="text-gray-500 hover:text-primary relative">
            <i class="fa fa-bell text-xl"></i>
            <span class="absolute -top-1 -right-1 w-4 h-4 bg-danger rounded-full text-white text-xs flex items-center justify-center">3</span>
          </button>
        </div>
      </header>

      <!-- 内容区域 -->
      <div class="flex-1 overflow-y-auto p-4">
        <!-- 操作栏 -->
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-3 mb-6" id="actionBar">
          <h3 class="text-xl font-bold">技能列表</h3>
          <div class="flex gap-3" id="adminActions">
            <button id="addSkillBtn" class="btn btn-primary flex items-center gap-2">
              <i class="fa fa-plus"></i> 添加技能
            </button>
            <div class="relative">
              <select id="skillCategoryFilter" class="pl-3 pr-8 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary appearance-none bg-white">
                <option value="all">所有分类</option>
                <option value="technical">技术技能</option>
                <option value="soft">软技能</option>
                <option value="management">管理技能</option>
              </select>
              <i class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 pointer-events-none"></i>
            </div>
          </div>
        </div>

        <!-- 统计卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <div class="skill-card">
            <div class="flex items-center justify-between mb-3">
              <h4 class="text-gray-500 font-medium">总技能数</h4>
              <i class="fa fa-cogs text-primary text-xl"></i>
            </div>
            <p class="text-3xl font-bold" id="totalSkills">42</p>
            <p class="text-sm text-success flex items-center mt-1"><i class="fa fa-arrow-up"></i> 12% 较上月</p>
          </div>
          <div class="skill-card">
            <div class="flex items-center justify-between mb-3">
              <h4 class="text-gray-500 font-medium">技术技能</h4>
              <i class="fa fa-code text-primary text-xl"></i>
            </div>
            <p class="text-3xl font-bold" id="technicalSkills">28</p>
            <p class="text-sm text-success flex items-center mt-1"><i class="fa fa-arrow-up"></i> 8% 较上月</p>
          </div>
          <div class="skill-card">
            <div class="flex items-center justify-between mb-3">
              <h4 class="text-gray-500 font-medium">技能覆盖率</h4>
              <i class="fa fa-pie-chart text-primary text-xl"></i>
            </div>
            <p class="text-3xl font-bold" id="skillCoverage">78%</p>
            <p class="text-sm text-danger flex items-center mt-1"><i class="fa fa-arrow-down"></i> 3% 较上月</p>
          </div>
        </div>

        <!-- 图表区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          <div class="skill-card">
            <h4 class="text-lg font-medium mb-4">技能分类分布</h4>
            <div class="h-64">
              <canvas id="skillCategoryChart"></canvas>
            </div>
          </div>
          <div class="skill-card">
            <h4 class="text-lg font-medium mb-4">技能需求趋势</h4>
            <div class="h-64">
              <canvas id="skillTrendChart"></canvas>
            </div>
          </div>
        </div>

        <!-- 技能表格 -->
        <div class="skill-card overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">技能ID</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">技能名称</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">熟练度</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">相关岗位</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" id="actionsHeader">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200" id="skillsTableBody">
              <!-- 技能数据将通过JavaScript动态加载 -->
              <tr class="animate-pulse">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">加载中...</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">加载中...</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">加载中...</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">加载中...</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">加载中...</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">加载中...</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </main>
  </div>

  <!-- 添加/编辑技能模态框 -->
  <div id="skillModal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-lg p-6 max-w-lg w-full mx-auto transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-xl font-bold text-primary" id="modalTitle">添加技能</h3>
        <button id="closeModalBtn" class="text-gray-500 hover:text-gray-700 text-xl">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <form id="skillForm" class="space-y-4">
        <input type="hidden" id="skillId" name="skillId">

        <div>
          <label for="skillName" class="block text-sm font-medium text-gray-700 mb-1">技能名称 <span class="text-danger">*</span></label>
          <input type="text" id="skillName" name="skillName" class="input-field" placeholder="请输入技能名称" required>
        </div>

        <div>
          <label for="skillCategory" class="block text-sm font-medium text-gray-700 mb-1">技能分类 <span class="text-danger">*</span></label>
          <select id="skillCategory" name="skillCategory" class="input-field" required>
            <option value="">请选择分类</option>
            <option value="technical">技术技能</option>
            <option value="soft">软技能</option>
            <option value="management">管理技能</option>
          </select>
        </div>

        <div>
          <label for="skillDescription" class="block text-sm font-medium text-gray-700 mb-1">技能描述</label>
          <textarea id="skillDescription" name="skillDescription" rows="3" class="input-field" placeholder="请输入技能描述"></textarea>
        </div>

        <div>
          <label for="skillLevel" class="block text-sm font-medium text-gray-700 mb-1">熟练度要求</label>
          <select id="skillLevel" name="skillLevel" class="input-field">
            <option value="beginner">入门</option>
            <option value="intermediate">中级</option>
            <option value="advanced">高级</option>
            <option value="expert">专家</option>
          </select>
        </div>

        <div>
          <label for="relatedPositions" class="block text-sm font-medium text-gray-700 mb-1">相关岗位</label>
          <input type="text" id="relatedPositions" name="relatedPositions" class="input-field" placeholder="请输入相关岗位，多个岗位用逗号分隔">
        </div>

        <div class="flex gap-3 justify-end pt-4 border-t border-gray-200">
          <button type="button" id="cancelBtn" class="btn btn-secondary px-6">取消</button>
          <button type="submit" class="btn btn-primary px-6" id="saveSkillBtn">保存</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // 初始化通用功能
      checkAuthentication();
      initUserInfo();
      initLogout();
      initSidebar();

      // 获取用户角色
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const userRole = userInfo.role || 'employee';

      // 根据角色显示/隐藏操作
      updateUIByRole(userRole);

      // 初始化图表
      function initCharts() {
        showLoading();
        // 使用真实API获取图表数据
        Promise.all([
          api.getSkillDistribution(),
          api.getSkillCategories()
        ]).then(([distributionData, categoriesData]) => {
          // 技能分类分布图表
          const categoryCtx = document.getElementById('skillCategoryChart').getContext('2d');
          new Chart(categoryCtx, {
            type: 'doughnut',
            data: {
              labels: distributionData.labels || ['技术技能', '软技能', '管理技能'],
              datasets: [{
                data: distributionData.values || [28, 10, 4],
                backgroundColor: ['#2563eb', '#10b981', '#f59e0b'],
                borderWidth: 0
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: {
                  position: 'right'
                }
              }
            }
          });

          // 技能需求趋势图表 - 这里简化处理，实际应根据真实API数据调整
          const trendCtx = document.getElementById('skillTrendChart').getContext('2d');
          new Chart(trendCtx, {
            type: 'line',
            data: {
              labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
              datasets: [{
                label: '技术技能',
                data: [15, 18, 22, 25, 26, 28],
                borderColor: '#2563eb',
                backgroundColor: 'rgba(37, 99, 235, 0.1)',
                tension: 0.3,
                fill: true
              }, {
                label: '软技能',
                data: [8, 9, 10, 9, 10, 10],
                borderColor: '#10b981',
                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                tension: 0.3,
                fill: true
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              scales: {
                y: {
                  beginAtZero: true
                }
              }
            }
          });

          hideLoading();
        }).catch(error => {
          hideLoading();
          showToast('加载图表数据失败: ' + (error.message || '未知错误'), 'error');
        });
      }

      // 加载技能数据
      function loadSkillsData() {
        showLoading();
        // 使用真实API调用替代模拟数据
        api.getAllSkills()
          .then(skills => {
            renderSkillsTable(skills);
            updateStatistics(skills);
            hideLoading();
          })
          .catch(error => {
            hideLoading();
            showToast('加载技能数据失败: ' + (error.message || '未知错误'), 'error');
          });
      }

      // 渲染技能表格
      function renderSkillsTable(skills) {
        const tableBody = document.getElementById('skillsTableBody');
        tableBody.innerHTML = '';

        skills.forEach(skill => {
          const row = document.createElement('tr');
          row.className = 'hover:bg-gray-50 transition-colors duration-150';

          // 技能ID
          const idCell = document.createElement('td');
          idCell.className = 'px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900';
          idCell.textContent = skill.id;
          row.appendChild(idCell);

          // 技能名称
          const nameCell = document.createElement('td');
          nameCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-900';
          nameCell.textContent = skill.name;
          row.appendChild(nameCell);

          // 技能分类
          const categoryCell = document.createElement('td');
          categoryCell.className = 'px-6 py-4 whitespace-nowrap';
          let categoryLabel = '';
          switch(skill.category) {
            case 'technical':
              categoryLabel = '<span class="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">技术技能</span>';
              break;
            case 'soft':
              categoryLabel = '<span class="px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800">软技能</span>';
              break;
            case 'management':
              categoryLabel = '<span class="px-2 py-1 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800">管理技能</span>';
              break;
          }
          categoryCell.innerHTML = categoryLabel;
          row.appendChild(categoryCell);

          // 熟练度
          const levelCell = document.createElement('td');
          levelCell.className = 'px-6 py-4 whitespace-nowrap';
          let levelLabel = '';
          switch(skill.level) {
            case 'beginner':
              levelLabel = '<span class="px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800">入门</span>';
              break;
            case 'intermediate':
              levelLabel = '<span class="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">中级</span>';
              break;
            case 'advanced':
              levelLabel = '<span class="px-2 py-1 text-xs font-medium rounded-full bg-purple-100 text-purple-800">高级</span>';
              break;
            case 'expert':
              levelLabel = '<span class="px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-800">专家</span>';
              break;
          }
          levelCell.innerHTML = levelLabel;
          row.appendChild(levelCell);

          // 相关岗位
          const positionsCell = document.createElement('td');
          positionsCell.className = 'px-6 py-4 text-sm text-gray-500';
          positionsCell.textContent = skill.relatedPositions || '无';
          row.appendChild(positionsCell);

          // 操作
          const actionsCell = document.createElement('td');
          actionsCell.className = 'px-6 py-4 whitespace-nowrap text-sm font-medium';

          // 根据角色显示不同操作
          if (userRole === 'admin') {
            actionsCell.innerHTML = `
              <button class="text-primary hover:text-primary/80 mr-3 edit-skill" data-id="${skill.id}"><i class="fa fa-edit"></i> 编辑</button>
              <button class="text-danger hover:text-danger/80 delete-skill" data-id="${skill.id}"><i class="fa fa-trash"></i> 删除</button>
            `;
          } else if (userRole === 'manager') {
            actionsCell.innerHTML = `
              <button class="text-primary hover:text-primary/80 mr-3 edit-skill" data-id="${skill.id}"><i class="fa fa-edit"></i> 编辑</button>
            `;
          } else {
            actionsCell.innerHTML = `
              <button class="text-primary hover:text-primary/80 view-skill" data-id="${skill.id}"><i class="fa fa-eye"></i> 查看</button>
            `;
          }

          row.appendChild(actionsCell);
          tableBody.appendChild(row);
        });

        // 添加编辑技能事件
        document.querySelectorAll('.edit-skill').forEach(btn => {
          btn.addEventListener('click', function() {
            const skillId = this.getAttribute('data-id');
            editSkill(skillId);
          });
        });

        // 添加删除技能事件
        document.querySelectorAll('.delete-skill').forEach(btn => {
          btn.addEventListener('click', function() {
            const skillId = this.getAttribute('data-id');
            if (confirm('确定要删除这个技能吗？')) {
              deleteSkill(skillId);
            }
          });
        });
      }

      // 更新统计数据
      function updateStatistics(skills) {
        const totalSkills = document.getElementById('totalSkills');
        const technicalSkills = document.getElementById('technicalSkills');
        const skillCoverage = document.getElementById('skillCoverage');

        if (totalSkills) totalSkills.textContent = skills.length;
        if (technicalSkills) {
          const techSkillsCount = skills.filter(skill => skill.category === 'technical').length;
          technicalSkills.textContent = techSkillsCount;
        }
        if (skillCoverage) skillCoverage.textContent = '78%'; // 模拟数据
      }

      // 编辑技能
      function editSkill(id) {
        showLoading();
        // 使用真实API请求获取技能详情
        api.getSkillById(id)
          .then(skill => {
            modalTitle.textContent = '编辑技能';
            skillIdInput.value = skill.id;
            document.getElementById('skillName').value = skill.name;
            document.getElementById('skillCategory').value = skill.category;
            document.getElementById('skillDescription').value = skill.description || '';
            document.getElementById('skillLevel').value = skill.level;
            document.getElementById('relatedPositions').value = skill.relatedPositions || '';

            openModal();
            hideLoading();
          })
          .catch(error => {
            hideLoading();
            showToast('获取技能详情失败: ' + (error.message || '未知错误'), 'error');
          });
      }

      // 创建新技能
      function createSkill(skillData) {
        showLoading();
        // 使用真实API请求
        api.createSkill(skillData)
          .then(() => {
            showToast('技能添加成功', 'success');
            closeModal();
            // 重新加载数据
            loadSkillsData();
            hideLoading();
          })
          .catch(error => {
            hideLoading();
            showToast('添加技能失败: ' + (error.message || '未知错误'), 'error');
          });
      }

      // 更新技能
      function updateSkill(id, skillData) {
        showLoading();
        // 使用真实API请求
        api.updateSkill(id, skillData)
          .then(() => {
            showToast('技能更新成功', 'success');
            closeModal();
            // 重新加载数据
            loadSkillsData();
            hideLoading();
          })
          .catch(error => {
            hideLoading();
            showToast('更新技能失败: ' + (error.message || '未知错误'), 'error');
          });
      }

      // 删除技能
      function deleteSkill(id) {
        showLoading();
        // 使用真实API请求
        api.deleteSkill(id)
          .then(() => {
            showToast('技能删除成功', 'success');
            // 重新加载数据
            loadSkillsData();
            hideLoading();
          })
          .catch(error => {
            hideLoading();
            showToast('删除技能失败: ' + (error.message || '未知错误'), 'error');
          });
      }

      // 移除页面内重复定义的showToast函数，使用common.js中的实现
      function showToast(message, type = 'success') {
        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform transition-all duration-500 ease-in-out z-50 opacity-0 translate-y-[-20px] ${
          type === 'success' ? 'bg-success text-white' : 'bg-danger text-white'
        }`;
        toast.textContent = message;

        // 添加到页面
        document.body.appendChild(toast);

        // 触发动画效果
        setTimeout(() => {
          toast.classList.remove('opacity-0', 'translate-y-[-20px]');
          toast.classList.add('opacity-100', 'translate-y-0');
        }, 10);

        // 自动关闭
        setTimeout(() => {
          toast.classList.remove('opacity-100', 'translate-y-0');
          toast.classList.add('opacity-0', 'translate-y-[-20px]');
          setTimeout(() => {
            document.body.removeChild(toast);
          }, 500);
        }, 3000);
      }
    });
  </script>
</body>
</html>